from TelnetServer import TelnetServer, EchoMode, TelnetCodes

class GameEngine( TelnetServer ):

    USER_PROMPT     = 0
    PASSWORD_PROMPT = 1
    PLAYING         = 2

    def __init__( self ):
        TelnetServer.__init__( self )
        self._states = {}
        self._count = 0
        self._clients = []
    
    def start( self ):
        print( 'Game engine starting up...' )
        TelnetServer.start( self )

    def prompt( self, id ):
        self.send( id, "\r" )
        self._count += 1;
        self.send( id, 'Prompt ' + str(self._count) + ': ' )

    def connectEvent( self, id ):

        self.send( id, "\\33]0;title goes here\\a" )
        self._states[ id ] = GameEngine.USER_PROMPT

        self.sendLine( id )
        self.sendLine( id, 'Welcome' )
        self.sendLine( id )

        self.send( id, 'Username: ' )

    def disconnectEvent( self, id ):
        print( 'id ' + str(id) + ' disconnected' )
        self._clients.remove( id )

    def dataEvent( self, id, data ):
        if self._states[ id ] == GameEngine.PLAYING:
            self.prompt( id )

        elif self._states[ id ] == GameEngine.USER_PROMPT:
            self._states[ id ] = GameEngine.PASSWORD_PROMPT
            self.setEchoMode( id, EchoMode.Password )
            self.send( id, 'Password: ' )

        elif self._states[ id ] == GameEngine.PASSWORD_PROMPT:
            self._states[ id ] = GameEngine.PLAYING
            self.setEchoMode( id, EchoMode.NoEcho )
            self.sendLine( id, '\r\nYou are now logged in' )
            self._clients.append( id )
            self.prompt( id )

    def loopEvent( self ):
        for client in self._clients:
            self.prompt( client )

game = GameEngine()
game.start()

